package com.example.pool.service;

import com.example.pool.utils.ThreadPoolUtil;

import java.util.concurrent.*;

public class CompletableServiceTest {

    static ThreadFactory threadFactory = Executors.defaultThreadFactory();
    static ExecutorService executorService = new ThreadPoolExecutor(3,3,600,
            TimeUnit.SECONDS,new ArrayBlockingQueue<>(3), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());


    private static ThreadPoolExecutor threadPool = ThreadPoolUtil.newFixedThreadPool(3,3,600L,new ArrayBlockingQueue<>(3),"twilioVerify");

    public static void test() throws Exception{
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            try {
                int i = 1 / 0;
                System.out.println(i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, executorService);
        voidCompletableFuture.get();
        executorService.shutdown();
    }

    public static void test2(){
        CompletableFuture[] completableFutures = new CompletableFuture[100];
        for (int i = 0; i < completableFutures.length; i++) {
            int finalI = i;
            completableFutures[i] = CompletableFuture.runAsync(() -> {
                if (finalI < 11) {
//                    System.out.println(1/0);
                    System.out.println("tt");
                } else {
                    System.out.println(finalI);
                }
            }, threadPool);
        }
        try {
            CompletableFuture.allOf(completableFutures).get();
            System.out.println("get");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            test2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
